package com.xfc.controller;

import com.xfc.common.config.RuoYiConfig;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.utils.ServletUtils;
import com.xfc.common.utils.file.FileUploadUtils;
import com.xfc.config.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lcj
 * @date 2022/08/16
 */
@Api(tags = "公共接口")
@Slf4j
@RestController
@RequestMapping("/api/common")
public class CommonController {

    /**
     * 通用上传请求
     */
    @ApiOperation(value = "图片上传")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "file", value =  "类型id",  dataType = "file",required = true),
    })
    @PostMapping("/upload")
    public Result<?> uploadFile(MultipartFile file) {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            log.info("上传地址："+filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = getUrl() + fileName;
            Map<String,String> ajax=new HashMap<>(2);
            ajax.put("fileName", url);
            ajax.put("url", fileName);
            return Result.ok(ajax);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     *
     * @return 服务地址
     */
    private String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    private static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
}
